package com.fly.demo.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.fly.demo.entity.Article;

import lombok.extern.slf4j.Slf4j;

/**
 * DataService
 */
@Slf4j
@Service
public class DataService
{
    List<Article> articles = new ArrayList<>();
    
    @Autowired
    List<DataInitor> dataInitors;
    
    /**
     * lock零长度的byte数组对象创建起来将比任何对象都经济
     */
    private byte[] lock = new byte[0];
    
    @PostConstruct
    public void init()
    {
        synchronized (lock)
        {
            initArticles();
            log.info("############## articles.size: {} ", articles.size());
            if (CollectionUtils.isEmpty(articles))
            {
                throw new RuntimeException("请先正确设置articles信息");
            }
        }
    }
    
    /**
     * 初始化articles
     * 
     * @return
     * @throws IOException
     */
    private void initArticles()
    {
        // 串行流,有一个DataInitor执行init成功就返回
        articles.clear();
        dataInitors.stream()
            .peek(d -> log.info("{}", d.getClass().getName())) // debug
            .anyMatch(d -> d.init(articles));
    }
    
    /**
     * 获取url数据列表
     * 
     * @return
     * @throws IOException
     */
    @Cacheable(cacheNames = "data", key = "'urls'", sync = true)
    public List<String> getUrls()
    {
        return getArticles().stream().map(Article::getUrl).collect(Collectors.toList());
    }
    
    /**
     * 获取articles
     * 
     * @return
     */
    public List<Article> getArticles()
    {
        return articles;
    }
}